package com.mySampleApplication.client.CodeRuleAtter;

import cn.hutool.core.date.DateUtil;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.mySampleApplication.client.dmp.DmpDto;
import com.mySampleApplication.client.dmp.DmpService;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.VerticalAlignment;
import com.smartgwt.client.util.JSOHelper;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.CloseClickEvent;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.HStack;
import com.smartgwt.client.widgets.layout.VLayout;

import java.util.*;

/**
 * 用法
 *      // 创建按钮和事件处理
 *      Button addButton = new Button("Add");
 *      addButton.setShowRollOver(true);
 *      addButton.setShowDown(true);
 *      addButton.addClickHandler(event -> showAddDialog(listGrid));
 *     private static void showAddDialog(ListGrid listGrid) {
 *       Window dialog=SShowWindow.getShowWindow();
 *       dialog.show();
 *     }
 */
public class CodeRuleAtterWindow {
    public static Window getShowWindow(boolean istrue,int width, int height, String title, final ListGridRecord record, ListGrid listGrid,ListGridRecord frecord){
        String modelId=frecord.getAttribute("db_model_id");
        String coderuleId=frecord.getAttribute("id");
        String bb=frecord.getAttribute("bb");
        final Window winModal = new Window();
        //winModal.setAutoSize(true);
        winModal.setWidth(width);
        winModal.setHeight(height);
        winModal.setTitle(title);
        winModal.setShowMinimizeButton(false);
        winModal.setIsModal(true);
        winModal.setShowModalMask(true);
        winModal.setCanDragReposition(true);
        winModal.setCanDragResize(true);
        winModal.centerInPage();
        winModal.addCloseClickHandler(new CloseClickHandler() {
            public void onCloseClick(CloseClickEvent event) {
                winModal.destroy();
            }
        });
        DynamicForm form = new DynamicForm();
        form.setPadding(20);
        form.setWidth100();
        form.setHeight(height-100);
        form.setNumCols(5);
        form.setCellPadding(10);
        TextItem fdmcField = new TextItem("fdmc", "分段名称");
        TextItem fdsxField = new TextItem("fdsx", "分段顺序");
        //TextItem fdlxField = new TextItem("fdlx", "分段类型");
        SelectItem fdlxField = new SelectItem("fdlx", "分段类型");
        TextItem lshcdField = new TextItem("lshcd", "流水号长度");
        TextItem lshbcField = new TextItem("lshbc", "流水号步长");
        TextItem lshgsField = new TextItem("lshgs", "流水号前缀");
        TextItem gdzField= new TextItem("gdz", "固定值");
        SelectItem zdsxmField= new SelectItem("zdsxm", "字段属性名");
        Map<String,String> mapk = new HashMap<>();
        mapk.put("object_id",modelId);
        DmpService.App.getInstance().getSelectByObjectId(mapk,"bt_data_object_attribute",new AsyncCallback<DmpDto>() {
            public void onSuccess(DmpDto result) {
               Map<String, String> keyValueMap = result.getKeyValueMap();
                zdsxmField.setValueMap(keyValueMap); // 设置静态数据
                //SC.say( "获取数据成功！");
            }
            public void onFailure(Throwable caught) {
                SC.warn("获取数据失败！");
            }
        });
        zdsxmField.hide();
        lshcdField.hide();
        lshbcField.hide();
        lshgsField.hide();
        gdzField.hide();
        //fdlxField.setWidth(240);
//        LinkedHashMap<String, String> valueMap = new LinkedHashMap<>();
//        valueMap.put("1", "流水号");
//        valueMap.put("2", "日期值");
//        valueMap.put("3", "固定值");
//        valueMap.put("4", "字段值");
        fdlxField.setValueMap(Dict.getFdlx()); // 设置静态数据
        fdlxField.addChangedHandler(new ChangedHandler() {
            @Override
            public void onChanged(ChangedEvent event) {
                String selectedValue = fdlxField.getValueAsString();
                if(selectedValue.equals("1")){
                    lshcdField.show();
                    lshbcField.show();
                    lshgsField.show();
                    gdzField.hide();
                    zdsxmField.hide();
                }else if(selectedValue.equals("2")){
                    gdzField.hide();
                    lshcdField.hide();
                    lshbcField.hide();
                    lshgsField.hide();
                    zdsxmField.hide();
                }
                else if(selectedValue.equals("3")){
                    gdzField.show();
                    lshcdField.hide();
                    lshbcField.hide();
                    lshgsField.hide();
                    zdsxmField.hide();
                }
                else if(selectedValue.equals("4")){
                    zdsxmField.show();
                    lshcdField.hide();
                    lshbcField.hide();
                    lshgsField.hide();
                    gdzField.hide();
                }
                //SC.say("选择的值为: " + modelId);
            }
        });
        TextItem bbField = new TextItem("bb", "版本");
        bbField.setValue(bb);
        bbField.disable();
//        item.setOptionDataSource(SDataSource.getDataSource());
//        item.setValueField("loginName");
//        item.setDisplayField("name");
        if (record != null) {
            // 更新已有记录
            fdmcField.setValue(record.getAttribute("fdmc"));
            fdsxField.setValue(record.getAttribute("fdsx"));
            fdlxField.setValue(record.getAttribute("fdlx"));
            zdsxmField.setValue(record.getAttribute("zdsxm"));
            gdzField.setValue(record.getAttribute("gdz"));
            lshcdField.setValue(record.getAttribute("lshcd"));
            lshbcField.setValue(record.getAttribute("lshbc"));
            lshgsField.setValue(record.getAttribute("lshgs"));
            String selectedValue = fdlxField.getValueAsString();
            if(selectedValue.equals("1")){
                lshcdField.show();
                lshbcField.show();
                lshgsField.show();
                gdzField.hide();
                zdsxmField.hide();
            }else if(selectedValue.equals("2")){
                gdzField.hide();
                lshcdField.hide();
                lshbcField.hide();
                lshgsField.hide();
                zdsxmField.hide();
            }
            else if(selectedValue.equals("3")){
                gdzField.show();
                lshcdField.hide();
                lshbcField.hide();
                lshgsField.hide();
                zdsxmField.hide();
            }
            else if(selectedValue.equals("4")){
                zdsxmField.show();
                lshcdField.hide();
                lshbcField.hide();
                lshgsField.hide();
                gdzField.hide();
            }
            // 禁用表单
            form.setDisabled(istrue);
        }

        Button saveButton = new Button("保存");
        saveButton.addClickHandler(event -> {
            if (form.validate()) {
                if (record != null) {
                    // 更新已有记录

                } else {
                    // 添加新记录
                    ListGridRecord newRecord = new ListGridRecord();
//                    newRecord.setAttribute("id", getuuid(32));
                    newRecord.setAttribute("fdmc", fdmcField.getValueAsString());
                    newRecord.setAttribute("fdsx", fdsxField.getValueAsString());
                    newRecord.setAttribute("fdlx", fdlxField.getValueAsString());
                    newRecord.setAttribute("zdsxm", zdsxmField.getValueAsString());
                    newRecord.setAttribute("gdz", gdzField.getValueAsString());
                    newRecord.setAttribute("lshcd", lshcdField.getValueAsString());
                    newRecord.setAttribute("lshbc", lshbcField.getValueAsString());
                    newRecord.setAttribute("lshgs", lshgsField.getValueAsString());
                    newRecord.setAttribute("bb", bbField.getValueAsString());

                    listGrid.addData(newRecord);
                }

                winModal.hide();
            }
        });

        Button cancelButton = new Button("关闭");
        cancelButton.addClickHandler(event -> winModal.hide());

        form.setItems(fdmcField,fdsxField,fdlxField,zdsxmField,gdzField,lshcdField,lshbcField,lshgsField,bbField);
        winModal.addItem(form);

        HLayout buttonLayout = new HLayout();
        buttonLayout.setMembersMargin(10);
        buttonLayout.setAlign(Alignment.RIGHT);
        buttonLayout.setWidth100();
        buttonLayout.setHeight(30);
        buttonLayout.setPadding(5);
        buttonLayout.setLayoutAlign(VerticalAlignment.BOTTOM);
        if(istrue!=true){
            buttonLayout.addMembers(saveButton, cancelButton);

        }else {
            buttonLayout.addMembers( cancelButton);
        }

        winModal.addItem(buttonLayout);
        HStack layoutTopRow = new HStack(10);
        layoutTopRow.setHeight(50);

        VLayout layoutMain = new VLayout();
        layoutMain.addMember(layoutTopRow);

        layoutMain.draw();
        return winModal;
    }
    public static Map<String, String> convertRecordToMap(Record record) {
        JavaScriptObject jsObj = record.getJsObj();
        return JSOHelper.convertToMap(jsObj);
    }
    public static String getuuid(int length) {

        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // 定义包含所有字母大小写的字符集合

        StringBuilder id = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            char c = characters.charAt(random.nextInt(characters.length())); // 从字符集合中随机选取一个字符

            id.append(c); // 将字符添加到字符串构建器中
        }
        return id.toString();
    }
}
